package com.feitubc.tools.fileimport.demo.controller;
   

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.feitubc.tools.fileimport.StrategyContext;
import com.feitubc.tools.fileimport.service.IBaseUploadFile;

/**
 * ImportFileController ：批量修改导入file
 * 
 * @author zhc
*/
@Controller
@RequestMapping("importFile")
public class ImportFileController extends BaseController {

    /** 视图前缀 */
    private static final String viewPrefix ="importFile";
    
    @Resource(name = "baseUploadFileService")
    private IBaseUploadFile baseUploadFileService;
    
    /***
     * 显示导入页面
     * @return
     */
    @RequestMapping(value = "/upload-page")
    public String uploadPage(Model model, String groupType){
    	if (StringUtils.isNotBlank(groupType)) {
    		model.addAttribute("fileStrategySettings", this.baseUploadFileService.getFileStrategySettingsByGropyType(groupType));
    	}
    	model.addAttribute("groupType", groupType);
    	return viewPrefix + "/upload-page";
    }
    
    /**
     * 文件上传方法
     * @return
     */
    @RequestMapping(value = "/upload")
    public String upload(@RequestParam(value = "uploadfile", required = false) MultipartFile uploadfile, 
    						StrategyContext strategyContext, Model model){
    	
		try {
			
			long startTime = System.currentTimeMillis();
			
			String filename = uploadfile.getOriginalFilename();
			strategyContext.setFilename(filename);
			strategyContext.setInputStream(uploadfile.getInputStream());
			
			// TODO 设置登录人信息默认值
			Long loginUserId = 999L;
			strategyContext.setCreateUserId(loginUserId);
			
			// 可设置其他值，供后续里面使用
//			strategyContext.putPreDataMap("test", "test");
			boolean result = this.baseUploadFileService.doUpload(strategyContext);
			
			long endTime = System.currentTimeMillis();
			
			//3.返回结果页面
			model.addAttribute("flag", result);
			model.addAttribute("useTime", (endTime - startTime));
			model.addAttribute("strategyContext", strategyContext);
			
		} catch (Exception e) {
			logger.error("ImportFileController#upload read readFile Exception :", e);
		}
		return viewPrefix + "/upload-result";
    }
}
